package com.boe.csb.web.controller.base;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.boe.csb.core.common.exception.CSBErrorCode;
import com.boe.csb.core.common.exception.CSBException;
import com.boe.csb.core.common.utils.FtpUtil;
import com.boe.csb.core.common.utils.MyRandomUtils;
import com.boe.csb.core.entity.SimplePageInfo;
import com.boe.csb.core.entity.po.BoeAppBean;
import com.boe.csb.core.entity.po.BoeUserFtp;
import com.boe.csb.core.service.user.BoeAppService;
import com.boe.csb.core.service.user.BoeUserFtpService;
import com.boe.csb.web.controller.BaseController;
import com.boe.csb.web.model.ResultModel;

/**
 * @author xinghe
 * @date 2017 - 03 - 28 上午10:41
 */
@RestController
@RequestMapping("/api/app/")
public class AppController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(AppController.class);

    @Autowired
    private BoeAppService boeAppService;
    @Autowired
    private BoeUserFtpService boeUserFtpService;
    

    /**
     * 新增APP展示详情
     *
     * @param
     */
    @RequestMapping(value = "add", method = RequestMethod.POST)
    public ResultModel<Long> addAppInfo(HttpSession session, @RequestBody JSONObject data) {
    	
    	String adminId = fetchUserId(session);
        Date time = new Date();
        String sql_id = "(";
        BoeAppBean boeapp = new BoeAppBean();
        boeapp.setName(data.getString("name"));
        String icon = data.getString("icon");
        if(!StringUtils.isBlank(icon)){
        	sql_id += returnNum(icon);
        }
        boeapp.setIcon(icon);
        boeapp.setSize(data.getString("size"));
        boeapp.setVersion(data.getString("version"));
        boeapp.setProductExplain(data.getString("productExplain"));
        String qrAndroid = data.getString("qrAndroid");
        if(!StringUtils.isBlank(qrAndroid)){
        	sql_id += ","+returnNum(qrAndroid);
        }
        boeapp.setQrAndroid(qrAndroid);
        String qrIos = data.getString("qrIos");
        if(!StringUtils.isBlank(qrIos)){
        	sql_id += ","+returnNum(qrIos);
        }
        boeapp.setQrIos(qrIos);
        String oneDisplay = data.getString("oneDisplay");
        if(!StringUtils.isBlank(oneDisplay)){
        	sql_id += ","+returnNum(oneDisplay);
        }
        boeapp.setOneDisplay(oneDisplay);
        String twoDisplay = data.getString("twoDisplay");
        if(!StringUtils.isBlank(twoDisplay)){
        	sql_id += ","+returnNum(twoDisplay);
        }
        boeapp.setTwoDisplay(twoDisplay);
        String threeDisplay = data.getString("threeDisplay");
        if(!StringUtils.isBlank(threeDisplay)){
        	sql_id += ","+returnNum(threeDisplay);
        }
        boeapp.setThreeDisplay(threeDisplay);
        String fourDisplay = data.getString("fourDisplay");
        if(!StringUtils.isBlank(fourDisplay)){
        	sql_id += ","+returnNum(fourDisplay);
        }
        boeapp.setFourDisplay(fourDisplay);
        String isDisplay = data.getString("isDisplay");
        if(!StringUtils.isBlank(isDisplay)){
        	 boeapp.setIsDisplay(isDisplay);
        }
        boeapp.setIsInvalid(0);
        boeapp.setCreateName(adminId);
        boeapp.setCreateTime(time);
        
        
        sql_id += ")";
    	
    	return ResultModel.success(boeAppService.addAppInfo(boeapp,sql_id));
    }

    /**
     * 查询列表，全部有效app列表
     * @param pageNum 页数
     * @param limit   数据量
     */
    @RequestMapping(value = "list" )
    public ResultModel<SimplePageInfo> findBoeApiInfoCount(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam Integer limit,@RequestParam(required=false) String display) {
        List<BoeAppBean> list = boeAppService.loadAppInfo(pageNum, limit,display);
        long count = boeAppService.countApp(display);
        return ResultModel.success(new SimplePageInfo(list,count));
    }
    
    /**
     * 查看app详情
     * @return
     */
    @RequestMapping(value = "find", method = RequestMethod.POST)
    public ResultModel<BoeAppBean> getHistorySearch(@RequestParam Long id){
    	return ResultModel.success(boeAppService.getAppInfo(id));
    }


    /**
     * 修改app展示详情
     *
     * @return
     */
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public ResultModel<Integer> queryPopularBoeApiList(HttpSession session,@RequestBody JSONObject data) {
    	
    	String adminId = fetchUserId(session);
    	Date time = new Date();
        String sql_id = "(";
        BoeAppBean boeapp = new BoeAppBean();
        boeapp.setId(data.getLong("id"));
        boeapp.setName(data.getString("name"));
        String icon = data.getString("icon");
        if(!StringUtils.isBlank(icon)){
        	sql_id += returnNum(icon);
        }
        boeapp.setIcon(icon);
        boeapp.setSize(data.getString("size"));
        boeapp.setVersion(data.getString("version"));
        boeapp.setProductExplain(data.getString("productExplain"));
        String qrAndroid = data.getString("qrAndroid");
        if(!StringUtils.isBlank(qrAndroid)){
        	sql_id += ","+returnNum(qrAndroid);
        }
        boeapp.setQrAndroid(qrAndroid);
        String qrIos = data.getString("qrIos");
        if(!StringUtils.isBlank(qrIos)){
        	sql_id += ","+returnNum(qrIos);
        }
        boeapp.setQrIos(qrIos);
        String oneDisplay = data.getString("oneDisplay");
        if(!StringUtils.isBlank(oneDisplay)){
        	sql_id += ","+returnNum(oneDisplay);
        }
        boeapp.setOneDisplay(oneDisplay);
        String twoDisplay = data.getString("twoDisplay");
        if(!StringUtils.isBlank(twoDisplay)){
        	sql_id += ","+returnNum(twoDisplay);
        }
        boeapp.setTwoDisplay(twoDisplay);
        String threeDisplay = data.getString("threeDisplay");
        if(!StringUtils.isBlank(threeDisplay)){
        	sql_id += ","+returnNum(threeDisplay);
        }
        boeapp.setThreeDisplay(threeDisplay);
        String fourDisplay = data.getString("fourDisplay");
        if(!StringUtils.isBlank(fourDisplay)){
        	sql_id += ","+returnNum(fourDisplay);
        }
        boeapp.setFourDisplay(fourDisplay);
        String isDisplay = data.getString("isDisplay");
        if(!StringUtils.isBlank(isDisplay)){
        	 boeapp.setIsDisplay(isDisplay);
        }
        boeapp.setUpdateName(adminId);
        boeapp.setUpdateTime(time);
        
        sql_id += ")";        
    	return ResultModel.success(boeAppService.updateAppInfo(boeapp,sql_id));
    }


    /**
     * 删除app展示
     *
     * @return
     */
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public ResultModel<Integer> queryRecommendBoeApiList(HttpSession session,@RequestParam Long id) {
        
    	return ResultModel.success(boeAppService.deleteAppInfo(id));
    }

    /**
     * 上线展示与下线
     *
     * @param apiId
     * @return
     */
    @RequestMapping(value = "display", method = RequestMethod.POST)
    public ResultModel<Object> addRecommendApi(HttpSession session,@RequestParam Long id,@RequestParam String display) {
    	CSBErrorCode errCode = boeAppService.displayAppInfo(id,Long.valueOf(display));
        return errCode == CSBErrorCode.SUCCESS ? ResultModel.success(null) : ResultModel.fail(errCode, null);
    }
    
    //上传图片
    @RequestMapping(value = "pic", method = RequestMethod.POST)
    public ResultModel<Long> uploadPic(HttpSession session, @RequestParam CommonsMultipartFile servicePic,@RequestParam String type ) throws IOException {
        String userId = fetchUserId(session);
        String filePath = FtpUtil.getDatePath();
        if (servicePic != null) {
        	
            String[] picArr = servicePic.getOriginalFilename().split("\\.");
            if (picArr.length >= 2) {
            	long size = servicePic.getSize();
                double scale = 1.0d ;
                if(size >= 200*1024){
                    if(size > 0){
                        scale = (200*1024f) / size  ;
                    }
                    
                }
                
                String idCard = MyRandomUtils.randomUUID() + "." + picArr[picArr.length - 1];
                if (!FtpUtil.upload(filePath, idCard, servicePic.getInputStream())) {
                    throw new CSBException(CSBErrorCode.UPLOAD_ERROR, "");
                }
                Long sequenceId = boeUserFtpService.insertUserFtp(Long.valueOf(userId), filePath, idCard, type, null);
                
                return ResultModel.success(sequenceId);
            }
        }
        return null;
    }
    
    @RequestMapping(value = "getImg", method = RequestMethod.GET)
    public void getImg(HttpServletResponse response,@RequestParam Long id,@RequestParam String type) throws IOException {
    	Long startTime = System.currentTimeMillis();
    	logger.info("获取图片开始时间："+startTime);
    	BoeUserFtp ftp = boeUserFtpService.findPathByAppPic(id, type);
        if (ftp == null) {
            logger.error("get pic by id:{}, type:{}!!",id,type);
            return;
        }
        String fileName = ftp.getFilename();
        String filePath = ftp.getFilepath();
        byte[] bytes = FtpUtil.download(filePath, fileName);
        if (bytes == null) {
            logger.info("pic is not found of path:{}, filelname:{}!!", filePath, fileName);
            return;
        }
        OutputStream os = response.getOutputStream();
        InputStream in = new ByteArrayInputStream(bytes);
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = in.read(buf, 0, 1024)) != -1) {
            os.write(buf, 0, len);
        }
        os.flush();
        Long endTime = System.currentTimeMillis();
        logger.info("获取图片结束时间：{}，耗时：{}",endTime,endTime-startTime);
    }
    
    private static String returnNum(String str){
    	String regEx="\\d+";   
    	Pattern p = Pattern.compile(regEx);
    	Matcher m = p.matcher(str);
    	while (m.find()) {  
            return m.group(0);  
        }  
    	return "0";
    }

}
